const router = require("koa-router")()
const { register, login } = require("../controller/user")
const loginCheck = require("../middleware/loginCheck")
const { SuccessModel, ErrorModel } = require("../res-module/index")

router.prefix("/api/user")

// router.get('/', function (ctx, next) {
//   ctx.body = 'this is a users response!'
// })

// router.get('/bar', function (ctx, next) {
//   ctx.body = 'this is a users/bar response'
// })

// 注册
router.post("/register", async function (ctx, next) {
  const { username, password } = ctx.request.body
  try {
    const newUser = await register(username, password)
    // ctx.body = {
    //   errno: 0,
    //   data: newUser
    // }
    ctx.body = new SuccessModel(newUser)
  } catch (error) {
    // 返回失败
    // ctx.body = {
    //   errno: 10001,
    //   message: `注册失败 - ${error.message}`
    // }
    ctx.body = new ErrorModel(10001, `注册失败 - ${error.message}`)
  }
})
// 登录
router.post("/login", async function (ctx, next) {
  const { username, password } = ctx.request.body
  const res = await login(username, password)
  if (res) {
    ctx.session.userInfo = { username }
    ctx.body = new SuccessModel()
  } else {
    ctx.body = new ErrorModel(10002, `登录验证失败`)
  }
})

// 获取用户信息
router.get("/info", loginCheck, async function (ctx, next) {
  const session = ctx.session
  ctx.body = new SuccessModel(session.userInfo)
})

module.exports = router
